var express = require('express');
var router = express.Router();
var UserSchema = require('../../modules/users')

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.post('/login', function(req, res, next) {
  let username = req.body.username
  let password = req.body.password
  let code = req.body.code
  // 字段验证
  if (!username) return res.json({code: 500, data: false, msg: '请填写用户名！'})
  if (!password) return res.json({code: 500, data: false, msg: '请填写密码！'})
  if (!code) return res.json({code: 500, data: false, msg: '请填写验证码！'})
  if (code !== req.session.captcha.toString()) return res.json({code: 500, data: false, msg: '验证码错误！'})

  // 用户校验
  var userConnect  = UserSchema.where({ username });
  new Promise((resolve, reject)=>{
    userConnect.findOne(function (err, doc){
      if (err) {
        reject(err);
      }else if(doc) {
        resolve(doc);
      } else {
        reject('用户名不存在！');
      }
    }).then((result)=>{
      if (password === result.password) {
        req.session.isLogin = true
        res.json({code: 200, data: result, msg: `用户: ${username}登陆成功！`})
      } else {
        res.json({code: 400, data: false, msg: `用户名或密码错误！`})
      }
    }).catch((err)=>{
      res.json({code: 500, data: false, msg: err})
    })
  })
  
});

module.exports = router;
